package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        //解析select
        List<Element> selectList = rootElement.selectNodes("//select");
        for (Element element : selectList) {
            MappedStatement mappedStatement = generateByElement(element, "SELECT");

            String key = namespace+"."+mappedStatement.getId();
            configuration.getMappedStatementMap().put(key,mappedStatement);

        }

        //解析update
        List<Element> updateList = rootElement.selectNodes("//update");
        for (Element element : updateList) {
            MappedStatement mappedStatement = generateByElement(element, "UPDATE");

            String key = namespace+"."+mappedStatement.getId();
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }

        //解析insert
        List<Element> insertList = rootElement.selectNodes("//insert");
        for (Element element : insertList) {
            MappedStatement mappedStatement = generateByElement(element, "INSERT");

            String key = namespace+"."+mappedStatement.getId();
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }

        //解析delete
        List<Element> deleteList = rootElement.selectNodes("//delete");
        for (Element element : deleteList) {
            MappedStatement mappedStatement = generateByElement(element, "DELETE");

            String key = namespace+"."+mappedStatement.getId();
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }

    }

    private MappedStatement generateByElement(Element element, String type){
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        String paramterType = element.attributeValue("paramterType");
        String sqlText = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setResultType(resultType);
        mappedStatement.setParamterType(paramterType);
        mappedStatement.setSql(sqlText);
        //设置type
        mappedStatement.setSqlCommandType(type);
        return mappedStatement;
    }


}
